package com.jyx.mybatis;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.jyx.mybatis.dao.DeptDao;
import com.jyx.mybatis.entity.Dept;

public class Test {

	public static void main(String[] args) {
		String resource = "mybatisConfig.xml";
		SqlSession session = null;
		try {

			Reader reader = Resources.getResourceAsReader(resource);
			session = new SqlSessionFactoryBuilder().build(reader).openSession();
			
//			Emp emp = new Emp();
//			emp.setDeptno("a97b1de472a911e787e5408d5c24561e");
//			emp.setJob("总管");
//			emp.setMgr("0");
//			emp.setName("小红");
//			emp.setSal(1000000);
//			session.insert("com.jyx.mybatis.dao.EmpDao.add",emp);
//			session.commit();
//			List<Emp> list = session.selectList("com.jyx.mybatis.dao.EmpDao.list");
//			for (Emp item : list) {
//				System.out.println(item.getName()+"-----"+item.getNo()+"-------" + item.getDept());
//			}
			
//			Reader reader = Resources.getResourceAsReader(resource);
//			SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
//			session = sqlMapper.openSession();
//			DeptDao deptDao = session.getMapper(DeptDao.class);
			
//			Dept dept = new Dept();
//			dept.setLoc("cese");
//			dept.setName("ces部门");
//			add(dept, session);
//			System.out.println(dept.getNo());
//			session.commit();
			
//			list(session);
//			delete(session,"c4c32e6e72a911e787e5408d5c24561e");
//			session.commit();
//			list(deptDao);
			
			
		} catch (IOException e) {
			e.printStackTrace();
			session.close();
			
		}
		
	}
	
	private static void delete(SqlSession session, String no) {
		session.delete("com.jyx.mybatis.dao.DeptDao.delete",no);
	}

	/**
	 * 添加
	 * @param dept
	 * @param session
	 */
	public static void add(Dept dept,SqlSession session){
		int i = session.insert("com.jyx.mybatis.dao.DeptDao.add",dept);
		System.out.println("插入条数："+i);
	}

	/**
	 * 查询全部
	 * @param session
	 */
	public static void list(SqlSession session){
		List<Dept> list = session.selectList("com.jyx.mybatis.dao.DeptDao.list");
		printInfo(list);
	}
	
	/**
	 * 用 session.getMapper(Clazz.class) 方式查询
	 * @param deptDao
	 */
	public static void list(DeptDao deptDao){
		List<Dept> list = deptDao.list();
		printInfo(list);
	}
	
	/**
	 * 根据ID查询
	 * @param session
	 */
	public static void getById(SqlSession session){
		Dept dept = session.selectOne("com.jyx.mybatis.dao.DeptDao.getById",2);
		System.out.println(dept.getNo());
		System.out.println(dept.getName());
		System.out.println(dept.getLoc());
	}
	
	public static void printInfo(List<Dept> list){
		for (Dept item : list) {
			System.out.println("no:"+item.getNo()+",name:"+item.getName()+",loc:"+item.getLoc()+"--------"+item.getEmpList());
		}
	}
	
}
